<?php

namespace app\Admin\controller;

use think\Controller;
use think\Request;
use think\facade\View;
use app\common\model\Activity as ActivityModel;
use app\common\model\ActivityCategory;
use app\common\service\Activity as ActivityService;

class Activity extends Controller
{
    protected $middleware = ['adminauth'];
    
    protected function initialize()
    {
        $activity_categories = ActivityCategory::order('sorder')->all();
        View::share('category', $activity_categories);
        View::share('status', ActivityModel::$status);
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $datas = ActivityModel::order('id desc')->paginate(20);
        return view('activity/index', ['datas' => $datas]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return view('activity/create');
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request, ActivityService $service)
    {
        $valiResult = $this->validate($request->post(), 'app\admin\validate\activity');
        if(true !== $valiResult)
        {
            $this->error($valiResult);
        }
        $data = $request->post() + $request->file();
        $info = $service->save($data);
        if(!$info['status'])
        {
            $this->error($info['msg']);
        }
        $this->success('添加成功');
    }   

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $data = ActivityModel::getOrFail($id);
        return view('activity/create', ['row' => $data]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, ActivityService $service, $id)
    {
        $valiResult = $this->validate($request->post(), 'app\admin\validate\activity');
        if(true !== $valiResult)
        {
            $this->error($valiResult);
        }
        $data = $request->post() + $request->file();
        $info = $service->save($data, $id);
        if(!$info['status'])
        {
            $this->error($info['msg']);
        }
        $this->success('修改成功', 'Activity/');
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        ActivityModel::destroy($id);
        return json(['status' => true]);
    }
}
